package com.thinkbig.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.StringTokenizer;

import com.thinkbig.segment.resource.ResourceLoader;
import com.thinkbig.segment.resource.Resourcer;
import com.thinkbig.segment.tokenize.Tokenizer;


public class HttpServer {
    public static void main(String args[]) {
        ServerSocket server_socket;
        try {
            ResourceLoader.loadDict("./data/dict/dict.txt");
            ResourceLoader.loadFavicon("./data/favicon.ico");
            server_socket = new ServerSocket(80);
            System.out.println("HttpServer running on port " + server_socket.getLocalPort());
            System.out.println("Please input \"http://localhost/${word}\" in your web-browser...");
            while (true) {
                Socket socket = server_socket.accept();
                System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
                try {
                    httpRequestHandler request = new httpRequestHandler(socket);
                    Thread thread = new Thread(request);
                    thread.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class httpRequestHandler implements Runnable {
    final static String CRLF = "\r\n";
    final String MODEL_STR = "<html>\n<head>\n<meta charset=\"utf-8\"/>\n</head>\n<body>\n%s</body>\n</html>\n";
    Socket socket;
    InputStream input;
    OutputStream output;
    BufferedReader br;

    public httpRequestHandler(Socket socket) throws Exception {
        this.socket = socket;
        this.input = socket.getInputStream();
        this.output = socket.getOutputStream();
        this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    public void run() {
        try {
            processRequest();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void processRequest() throws Exception {
        String headerLine = null;
        while ((headerLine = br.readLine()) != null) {
            System.out.println("The client request is " + headerLine);
            if (headerLine.equals(CRLF) || headerLine.equals(""))
                break;
            StringTokenizer s = new StringTokenizer(headerLine);
            String temp = s.nextToken();
            if (temp.equals("GET")) {
                String query = s.nextToken();
                if ("/favicon.ico".equals(query)) {
                    output.write(Resourcer.FAVICON);
                    continue;
                }
                query = URLDecoder.decode(query, "utf-8");
                if (query.startsWith("/")) {
                    query = query.substring(1);
                }
                String segResult = Tokenizer.tokenize(query);
                output.write(String.format(MODEL_STR, segResult).getBytes("utf-8"));
            }
        }

        try {
            output.close();
            br.close();
            socket.close();
        } catch (Exception e) {
        }
    }
}
